<?php

namespace Swof\Event;

use Closure;
use Exception;

class Event
{
    /**
     * Event array
     *
     * @var array
     */
    protected $events = [];

    /**
     * Note: get event
     *
     * @param null $name
     * @return array|mixed
     * @author: Zhao Zhiqiang
     * @since: 2021/6/2 17:26
     */
    public function getEvents($name = null)
    {
        return ! $name || ! isset($this->events[$name])
            ? $this->events[$name]
            : $this->events;
    }

    /**
     * Note: Register event
     *
     * @param string $name
     * @param Closure|array $callback
     * @author: Zhao Zhiqiang
     * @since: 2021/6/2 17:35
     */
    public function register(string $name, $callback)
    {
        $name = strtolower($name);

        $this->events[$name]['callback'] = $callback;
    }

    /**
     * Note: trigger an event
     *
     * @param string $name
     * @param array $parameters
     * @return mixed
     * @throws Exception
     * @author: Zhao Zhiqiang
     * @since: 2021/6/2 17:39
     */
    public function trigger(string $name, array $parameters = [])
    {
        if (isset($this->events[$name])) {
            return $this->events[$name]['callback']($parameters);
        }

        throw new Exception('event not exists');
    }
}